package com.hulei.studyproject.controller;

import com.hulei.studyproject.druid.annotation.Master;
import com.hulei.studyproject.entity.AttachmentFile;
import com.hulei.studyproject.nacos.listener.FastDFSClientUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @Title: FileController
 * @Description: TODO
 * @author: hulei
 * @date: 2023/8/9 17:27
 * @Version: 1.0
 */
@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
@Slf4j
public class FileController {

    private final JdbcTemplate jdbcTemplate;

    @PostMapping("/upload")
    @Master
    public void uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request){
        if(!FastDFSClientUtil.getFileExt(file.getOriginalFilename()).toLowerCase().matches("bmp|png|gif|jpeg|jpg|pdf|doc|docx|xls|xlsx|ico|apk")){
            throw new RuntimeException("上传文件格式不符合规范!");
        }
        log.info("开始上传图片");
        log.info("调用FastDFSClientUtil,图片名称：" + file.getOriginalFilename());
        String[] fileResults = FastDFSClientUtil.uploadFile(file, file.getOriginalFilename());
        if (fileResults == null) {
            throw new RuntimeException("上传失败!");
        }
        String fileDirectory = fileResults[0];
        String filePath = fileResults[1];
        AttachmentFile attachmentFile = AttachmentFile.builder()
                .id(new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())).fileDirectory(fileDirectory)
                .filePath(filePath)
                .build();
        System.out.println("上传文件返回结果:"+ attachmentFile);
        String sql = "insert into att_file(id,file_directory,file_path) values (?,?,?)";
        int result = jdbcTemplate.update(sql, attachmentFile.getId(), attachmentFile.getFileDirectory(), attachmentFile.getFilePath());
        System.out.println("保存文件上传信息结果："+result);
    }

    /**
     * 文件下载
     * @param fileId 文件id
     * @param response 响应
     */
    @GetMapping("/download")
    @Master
    public void downLoadFile(@RequestParam("fileId") String fileId, HttpServletResponse response){
        System.out.println("fileId："+fileId);
        AttachmentFile attachmentFile = jdbcTemplate.queryForObject("select * from att_file a where a.id = ?",
                new BeanPropertyRowMapper<>(AttachmentFile.class), fileId);
        if (attachmentFile != null) {
            InputStream fis = FastDFSClientUtil.downloadFile(attachmentFile.getFileDirectory(), attachmentFile.getFilePath());
            try {
                // 以流的形式下载文件。
                assert fis != null;
                byte[] buffer = new byte[fis.available()];
                fis.read(buffer);
                fis.close();
                // 清空response
                response.reset();
                response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("随机文件", StandardCharsets.UTF_8));
                OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
                toClient.write(buffer);
                toClient.flush();
                toClient.close();
            } catch (IOException ex) {
               throw new RuntimeException(ex.getMessage());
            }
        } else {
           throw new RuntimeException("文件不存在");
        }
    }

}
